// pages/author/author.js
const db = wx.cloud.database();
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		/* 		loginParams:{
					encryptedData:'',
					rawData:'',
					iv:'',
					signature:'',
					code:''
					
				} */
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {

	},

	async hendleUserInfo(e) {
		const {
			encryptedData,
			rawData,
			iv,
			signature
		} = e.detail;
		console.log(e);


		/* 		wx.login({}).then(res => {
					const code = res.code;
					const loginParams = {encryptedData,rawData,iv,signature,code}
					this.setData({
						loginParams
					});
				})
				const res = await wx.request({
					url:"https://api-hmugo-web.itheima.net/api/public/v1/users/wxlogin",
					data: this.data.loginParams,
					method:"POST",
					success: ((res) => {
						console.log(res);
					})
				}) */
		wx.login({}).then(res => {
			const {
				code
			} = res;
			console.log(code);
			if (res.code) {
				wx.request({
					url: 'https://api.weixin.qq.com/sns/jscode2session',
					data: {
						appid: 'wx50c10eea9e50a11d',
						secret: '34356baa8fa30ab98b920bd825e45bd0',
						js_code: code,
						grant_type: 'authorization_code'
					},
					success: ((User_res) => {
						wx.setStorageSync('openid', User_res.data.openid);
						let {
							openid
						} = User_res.data;
						let userID = openid.substring(openid.length - 7)
						wx.getUserInfo({
							success: ((infoRes) => {
								wx.setStorageSync('token', true)
								db.collection('user').where({
									_openid: openid
								}).get({
									success: ((res) => {
										console.log(
											res
											.data
											);
										if (res.data
											.length ==
											0
										) {
											db.collection(
													'user'
												)
												.add({
													data: {
														nickName: infoRes
															.userInfo
															.nickName,
														avatarurl: infoRes
															.userInfo
															.avatarUrl,
														code: res
															.code,
														userid: userID
													}
												})
										}
									wx.navigateBack({delta:1});
									})
								})

							})
						})
					})
				})

			}
		})


	}
})
